All files / src/app/api/admin/workflows/[id]/trigger route.ts

0% Statements 0/68
100% Branches 0/0
0% Functions 0/1
0% Lines 0/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                         
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { WorkflowEngine } from "@/lib/workflows";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

const LOG_CATEGORY = "ADMIN_WORKFLOW_TRIGGER_API";

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * POST /api/admin/workflows/[id]/trigger
 * Manually trigger a workflow for testing
 */
async function handlePost(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const workflowId = parseInt(id);

  if (isNaN(workflowId)) {
    throw ApiError.badRequest("Invalid workflow ID");
  }

  const body = await request.json();
  const { userId, triggerData } = body;

  if (!userId) {
    throw ApiError.badRequest("userId is required");
  }

  const workflow = await prisma.marketingWorkflow.findUnique({
    where: { id: workflowId } });

  if (!workflow) {
    throw ApiError.notFound("Workflow");
  }

  // Start the workflow
  const executionId = await WorkflowEngine.startWorkflow(
    workflow,
    userId,
    triggerData || {}
  );

  if (!executionId) {
    throw ApiError.badRequest("Failed to start workflow (user may already be in this workflow)");
  }

  logger.info("Workflow triggered", { category: LOG_CATEGORY, workflowId, userId, executionId });

  return successResponse({
    executionId,
    message: "Workflow triggered successfully" });
}

export const POST = withErrorHandling(withAdmin(handlePost));